package net.towee.model.account.impl;

import java.util.ArrayList;
import java.util.List;

import net.towee.model.account.Board;
import net.towee.model.account.Gadget;
import net.towee.model.group.GroupIdentity;
import net.towee.model.group.impl.GroupIdentityImpl;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.PostLoad;
import com.google.code.morphia.annotations.Reference;

/**
 * Implementation of account board interface
 * @author c58
 */
@Embedded
public class BoardImpl implements Board {
	private String id;
	
	// Name of board
	private String name;
	
	// Attached gadgets
	private List<Gadget> gadgets;
	
	// Attached groups
	@Reference private List<GroupIdentity> groups;

	public BoardImpl() {}
	public BoardImpl(String id) {
		this.id = id;	
	}
	public BoardImpl(String id, String name) {
		this.id = id;
		this.name = name;
		this.gadgets = new ArrayList<Gadget>();
		this.groups = new ArrayList<GroupIdentity>();
	}
	
	@PostLoad
	private void createEmptyArrays(){
		if(gadgets == null)
			gadgets = new ArrayList<Gadget>();
		if(groups == null)
			groups = new ArrayList<GroupIdentity>();		
	}
	
	@Override
	public String getId() {
		return id;
	}
	
	@Override
	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public List<Gadget> getGadgets() {
		return gadgets;
	}

	@Override
	public void addGadget(Gadget w) {
		if(!gadgets.contains(w))
			gadgets.add(w);
	}

	@Override
	public void deleteGadget(Gadget w) {
		gadgets.remove(w);
	}
	@Override
	public List<GroupIdentity> getAttachedGroups() {
		return groups;
	}
	@Override
	public void attachGroup(GroupIdentity group) {
		if(!groups.contains(group))
			groups.add(group);
	}
	@Override
	public boolean detachGroup(GroupIdentity group) {
		return groups.remove(group);
	}
	
	@Override
	public boolean detachGroup(String groupId) {
		return detachGroup(new GroupIdentityImpl(groupId));
	}

	@Override
	public boolean equals(Object o) {
		if(this == o)
			return true;
		if(o instanceof Board && (getId().equals( ((Board)o).getId() )))
			return true;
		if(o instanceof Board && getName() !=null && getName().equals( ((Board)o).getName() )) 
			return true;
		
		return false;
	}
	
	@Override
	public boolean containsGadget(String canonicalName) {
		return gadgets.contains( new GadgetImpl(canonicalName) );
	}
	
	@Override
	public void deleteGadget(String gadgetId) {
		gadgets.remove( new GadgetImpl(gadgetId) );
	}
	@Override
	public boolean hasAttachedGroup(String id) {
		return groups.contains( new GroupIdentityImpl(id) );
	}
}
